package com.xingxuecn.limit.dao.impl;

import com.xingxuecn.limit.common.model.dto.Menu;
import com.xingxuecn.limit.common.model.dto.Role;
import com.xingxuecn.limit.common.model.dto.RoleMenu;
import com.xingxuecn.limit.common.utils.DbUtils;
import com.xingxuecn.limit.dao.RoleMenuDao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author Kris at 2018/9/12 14:39
 */
public class RoleMenuDaoImpl implements RoleMenuDao {
    QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

    @Override
    public int add(RoleMenu roleMenu) throws SQLException {
        String sql = "insert into role_menu(menu_id,role_id) values(?,?)";
        return queryRunner.execute(sql, new Object[]{
                roleMenu.getMenu_id(),
                roleMenu.getRole_id()
        });
    }

    @Override
    public int delete(RoleMenu roleMenu) throws SQLException {
        String sql = "delete from role_menu where menu_id = ? and role_id = ?";
        return queryRunner.execute(sql, new Object[]{
                roleMenu.getMenu_id(),
                roleMenu.getRole_id()
        });
    }

    @Override
    public List<Menu> loadMenuByRole(Integer roleId) throws SQLException {
        String sql = "select m.* from menu m inner join role_menu rm on rm.menu_id = m.id where rm.role_id = ?";
        return queryRunner.query(sql,new BeanListHandler<Menu>(Menu.class),new Object[]{roleId});
    }
}
